Attribute VB_Name = "modCommunications"
Option Explicit

Public Enum DP5_DPP_TYPES
    dppDP5
    dppPX5
    dppDP5G
    dppMCA8000D
    dppTB5
    dppDP5X
End Enum

Public Enum CommType
    commRS232 = 0
    commUSB = 1
    commSockets = 2
    commNone = 3
End Enum

Public Timeout_flag As Boolean

Public Const RS232 = 0
Public Const USB = 1
Public Const ETHERNET = 2

Public Const ETHERNET_TIMEOUT = 1000   ' default timeout of 1000mS
Public Const INTERNET_TIMEOUT = 3000   ' 3 seconds if DP5 is on different subnet than this PC
Public Const RS232_TIMEOUT = 2500      ' default timeout of 2500mS (8K spectrum ~2.2s)
Public Const USB_TIMEOUT = 500         ' default timeout of 500mS

Public Const ETHERNET_KEEPALIVE = 1500 ' send a keep-alive after 1.5s of interface inactivity
Public Const Retries = 2   ' total of 3 attempts

Public OutStr As String
Public InPacketType As Integer
Public PlotColor As Long
Public Scope(0 To 2047) As Byte  ' make this a structure, with scope info?
Public MiscData(512) As Byte
Public CommError As Boolean

Public strCommStatus As String
Public Packet_Received As Boolean

Public UDP_offset As Integer
Public USB_Default_Timeout As Boolean
Public isDppFound(RS232 To ETHERNET) As Boolean

Public USBDeviceTest As Boolean

Public RS232HeaderReceived As Boolean
Public RS232PacketPtr As Integer
Public RS232ComPortTest As Boolean
Public Const MAX_DISPLAY_ENTRIES = 4

Public Function SendPacketRS232(IntCtrl As Object, ByRef Buffer() As Byte, ByRef PacketIn() As Byte) As Boolean
    Dim bytesWritten As Long, bytesRead As Long
    Dim success As Boolean
    Dim curStartTime As Currency
    Dim isExpired As Boolean
    Dim strLog As String
    Dim i As Long
    Dim PLen As Long
    
    PLen = (Buffer(4) * 256) + Buffer(5) + 7

    ACK_Received = False
    Packet_Received = False ' a response packet is always expected
    PIN.STATUS = &HFF   ' packet invalid - will be overwritten soon by response/ACK packet

    ' send the packet
    'For i = 0 To POUT.LEN + 7
    For i = 0 To PLen
        IntCtrl.Output = Chr(Buffer(i))
    Next i
    Timeout_flag = False
    curStartTime = msTimeStart()
    Do
        DoEvents    ' receive bytes and parse packet
        isExpired = msTimeExpired(curStartTime, 1000)
        If (isExpired) Then Timeout_flag = True
    Loop While (PIN.STATUS = &HFF) And (Timeout_flag = False)  ' wait for ACK or timeout
    If Timeout_flag Then
        strLog = strLog + "Timeout: no response packet!" + vbCrLf
        SendPacketRS232 = False
    Else
        SendPacketRS232 = True
    End If
End Function


